<template>
	<div style="padding-top: 5px;  background-color: white">
<!--    顶部信息-->
    <div style="display: flex;">
      <JInput style="margin-left: 5px; width: 220px" v-model="billNo" placeholder="如二维码损坏，可输入完整票号查询" @click="doSearch" />
      <JButton @click="doSearch" type="info">搜索</JButton>
      <div style="margin-left: 30px;color: #4FC1E9;line-height: 28px;height: 28px;">
        请扫描销售单。
        适用场景：批量收当天 现结 客户欠款,并可同时做退货抵扣。
      </div>
    </div>
    <div style="display: flex;margin-top: 5px;margin-left: 5px;">
      <fieldset style="padding: 13px;border: 1px solid rgba(0,0,0,0.2);">
        <legend>票据信息</legend>
        <!--        要收款的票据-->
        <j-grid
            ref="receiptListRef" v-model="receiptList"
            :columns="receiptFields" :height="310" @edit-closed="editClose" :width="1100"
        />
      </fieldset>

      <div style="flex: 1;padding-left: 10px;">
<!--        账户收款信息-->
        <account ref="accountRef" @clearData="clearData" />
      </div>
    </div>
<!--    关联退货-->
    <fieldset style="padding: 13px;margin:  5px;border: 1px solid rgba(0,0,0,0.2);">
      <legend>退货信息</legend>
      <backList ref="backRef" @changeVal="changeBack" />
    </fieldset>
<!--    弹出抵扣-->
    <dikou ref="dikouRef" @changeVal="changeDikou" />
    <j-dialog v-if="showEditPop" v-model="showEditPop" title="修改单据" :width="1200" draggable top="10px" :z-index="9">
      <Bill ref="billRef" :page="whichPage" :right="false" @saveSuc="saveSuc"></Bill>
    </j-dialog>
	</div>
</template>

<script>
// 扫单收款
import tool from '@/utils/tool';
import bus from '@/store/bus';
import top from './scanreceipt/top.vue'
import dikou from './scanreceipt/dikou.vue'
import backList from './scanreceipt/backList.vue'
import account from './scanreceipt/account.vue'
import Bill from '../Bill.vue'
export default {
	name: 'scanreceipt',
	components: { top, dikou , backList, account, Bill},
	data() {
		return {
			page: 'scanreceipt',
      receiptFields: [
        {type: 'index', width: 40},
        {field: 'billDate', width: 100,title:'日期'},
        {field: 'buName', width: 180,title:'客户',align: 'left'},
        {field: 'billStateName', width: 80,title:'状态'},
        {field: 'billNo', width: 100,title:'票号',canClick: true},
        {field: 'transTypeName', width: 80,title:'业务类型'},
        {field: 'totalAmount', width: 80,title:'总金额',align: 'right',sum: true,formatter:'formatMoney'},
        {field: 'leftAmount', width: 80,title:'欠款',align: 'right',sum: true,formatter:'formatMoney'},
        {field: 'nowCheck', width: 90,title:'本次收款',align: 'right',sum: true,editor: {component:'input', autoselect:true,events:{
          keydown:(cell, key) => {
            if(key.key === 'Enter') {
              this.$refs.receiptListRef.setActiveCell(cell.row, 'yhAmount')
            }
            if(key.key === 'ArrowRight') {
              this.$refs.receiptListRef.setActiveCell(cell.row, 'yhAmount')
            }
            if(key.key === 'ArrowDown') {
              if((cell.data.length - 1) > cell.$rowIndex) {
                this.$refs.receiptListRef.setActiveCell(cell.data[cell.$rowIndex+1], 'nowCheck')
              }
            }
            if(key.key === 'ArrowUp') {
              if(cell.$rowIndex > 0) {
                this.$refs.receiptListRef.setActiveCell(cell.data[cell.$rowIndex-1], 'nowCheck')
              }
            }
          }
            }},formatter:'formatMoney'},
        {field: 'yhAmount', width: 90,title:'收款优惠',align: 'right',sum: true,editor: {component:'input', autoselect:true,events:{
              keydown:(cell, key) => {
                if(key.key === 'Enter') {
                  this.$refs.receiptListRef.setActiveCell(cell.row, 'yhAmount')
                }
                if(key.key === 'ArrowLeft') {
                  this.$refs.receiptListRef.setActiveCell(cell.row, 'nowCheck')
                }
                if(key.key === 'ArrowDown') {
                  if((cell.data.length - 1) > cell.$rowIndex) {
                    this.$refs.receiptListRef.setActiveCell(cell.data[cell.$rowIndex+1], 'yhAmount')
                  }
                }
                if(key.key === 'ArrowUp') {
                  if(cell.$rowIndex > 0) {
                    this.$refs.receiptListRef.setActiveCell(cell.data[cell.$rowIndex-1], 'yhAmount')
                  }
                }
              }
            } },formatter:'formatMoney'},
        {field: 'jy', width: 80,title:'结余',align: 'right',sum: true,formatter:'formatMoney'},
        {field: '', width: 90,title:'操作',align: 'right',btns:[{id: 'id', label: '改单',click: (row) => {
              this.editBill(row)
            }},{id:'del',label:'清除', click: (row) => {
              this.del(row)
            }}]},
      ],
      receiptList: [], // 待收款的列表
      back: {
        remark: '',
        billDate: '',
        list: []
      }, // 要退货的商品列表
      invoice: {
        billState: '',
        state: '',
        dikouList: [],
      },
      code: '', // 扫描的票据
      receiptData: 0, // 自动填充时间的类型
      showEditPop: false,
      whichPage: 's-in',
      altBillNo: '',
      altRow: {},
      //
			altDate: true,
			isRelate: true,
			autoVerify: false,
			currentMenuId: 0,
			billState: '',
			totalAmount: '', // 关联退货的总金额
			//
			billDate: '',
			billId: '',
			accId: '',
			accName: '',
			accAmount: '',
			accId1: '',
			accName1: '',
			accAmount1: '',
			doId: '',
			doName: '',
			remark: '',
			yhAmount: '',
			useDate: 'useBillDate', // 使用日期 useCurrentDate
			receiptType: 'byBill', // byBuId
			tuiRemark: '',
			yinsAmount: 0,
			billNo: '',
		};
	},
	activated() {
		bus.$on('scan-ret', this.scanRet);
	},
	deactivated() {
		bus.$off('scan-ret', this.scanRet);
	},
	methods: {
		doSearch(billNo) {
      this.billNo = billNo
			if (this.billNo) {
				tool.post('scan/getIdByNo', { billNo: this.billNo }).then((ret) => {
					if (ret.stat) {
						this.scanRet({ code: ret.data });
					}
				});
			}
		},
    editBill (row) {
      this.altRow = row
      // this.url += 'main/s-in?showMenu=false'
      this.altBillNo = row.billNo
      if(row.transType === 150601) {
        this.whichPage = 's-in'
      }
      else if(row.transType === 150602) {
         this.whichPage = 's-out'
      }
      else {
        tool.warning('不支持换货单修改')
      }
      this.showEditPop = true
      setTimeout(() => {
        this.$refs.billRef.popOpenBill(row.billNo)
      },300)
    },
    // 弹出改单保存成功
    saveSuc () {
      this.showEditPop = false
      this.$nextTick(() => {
        setTimeout(() => {
          if(this.altRow && this.altRow.id) {
            tool.post('receipt/getBillById', {billId: this.altRow.id}).then(ret => {
              if(ret.stat) {
                this.altRow.totalAmount = ret.data.totalAmountReal
                this.altRow.leftAmount = tool.xe.subtract(ret.data.arrearsReal, ret.data.hxAmount)
                this.altRow.nowCheck = this.altRow.leftAmount
                this.altRow.billState = ret.data.billState
                this.altRow.billStateName = ret.data.billStateName
                this.updateAll()
              }
            })
          }
        }, 150)
      })
    },
    scanRet({ code }) {
      this.code = code;
      let arr = code.split('-')
      if(['150601','150602','150603'].indexOf(arr[0]) === -1) return tool.err('只支持销售单据');
      this.scanBill();
    },
    scanBill() {
      if (!this.code) return;
      this.invoice.dikouList = [];
      this.invoice.goods = [];
      tool.post('scan/findReceiptById', { scanInfo: this.code, method: 'verify' }, true).then((ret) => {
        if (ret.stat) {
          if(this.receiptList.length > 0) {
            if(ret.data.buId !==  tool.xe.toNumber(this.receiptList[0].buId)) {
              return tool.warning('只能同时收 1 个客户票据')
            }
          }
          // 设置收款列表，原来只收一条，现在可以收同一商户多条
          let obj = {
            id: ret.data.id,
            billType: ret.data.billType,
            billDate: ret.data.billDate,
            billStateName: ret.data.billStateName,
            buName: ret.data.buName,
            buId: ret.data.buId,
            billState: ret.data.billState,
            billNo: ret.data.billNo,
            transType: ret.data.transType,
            transTypeName: ret.data.transTypeName,
            totalAmount: ret.data.totalAmount,
            leftAmount: ret.data.leftAmount,
            nowCheck: ret.data.leftAmount,
            yhAmount: 0,
            jy: 0,
          }
          for (let i = 0; i < this.receiptList.length; i++) {
            if(this.receiptList[i].id === obj.id) {
              this.receiptList.splice(i, 1)
            }
          }
          this.receiptList.push(obj)
          ret.data.dikouList.map(row => {
            row.leftAmount = -row.leftAmount
            row.totalAmount = -row.totalAmount
            row.nowCheck = -row.leftAmount
          })
          this.$refs.dikouRef.open(ret.data.dikouList);
          this.$refs.backRef.setData(ret.data.goods);
          // 如果是要填充时间到票据时间
          if(this.receiptData === 1) {
            this.$refs.accountRef.setDate(obj.billDate)
            this.$refs.backRef.setDate(obj.billDate)
          }
          this.$refs.accountRef.setDo({id: ret.data.salesId, name: ret.data.salesName})
          this.updateAll()
        } else {
          this.clearData();
        }
      });
    },
    // 选中抵扣票据
    changeDikou (dikou) {
      for (let i = 0; i < dikou.length; i++) {
        let row = dikou[i]
        let obj = {
          id: row.id,
          billType: row.billType,
          billDate: row.billDate,
          transType: row.transType,
          billStateName: row.billStateName,
          buName: row.buName,
          buId: row.buId,
          billState: row.billState,
          billNo: row.billNo,
          transTypeName: row.transTypeName,
          totalAmount: row.totalAmount,
          leftAmount: row.leftAmount,
          nowCheck: row.leftAmount,
          yhAmount: 0,
        }
        for (let i = 0; i < this.receiptList.length; i++) {
          if(this.receiptList[i].id === obj.id) {
            this.receiptList.splice(i, 1)
          }
        }
        this.receiptList.push(obj)
      }
      this.updateAll()
    },
    changeBack (back) {
      this.back = back
      this.updateAll()
    },
    del (row) {
      for (let i = 0; i < this.receiptList.length; i++) {
        if(this.receiptList[i].id === row.id)
          this.receiptList.splice(i, 1)
      }
      this.updateAll()
    },
    editClose (cell) {
      let field = cell.column.property
      let transType = cell.row.transType
      if(field === 'nowCheck') {
        if(transType === 150602) {
          cell.row.nowCheck = -Math.abs(tool.xe.toNumber(cell.row.nowCheck))
        }
        else {
          cell.row.nowCheck = tool.xe.toNumber(cell.row.nowCheck)
        }
      }
      if(field === 'yhAmount') {
        if(transType === 150602) {
          cell.row.yhAmount = -Math.abs(tool.xe.toNumber(cell.row.yhAmount))
        }
        else {
          cell.row.nowCheck = tool.xe.toNumber(cell.row.nowCheck)
        }
      }
      cell.row.jy = tool.xe.subtract(tool.xe.subtract(cell.row.leftAmount, cell.row.nowCheck), cell.row.yhAmount)
      this.updateAll()
    },
    updateAll () {
      this.$nextTick(() => {
        this.$refs.receiptListRef.updateFooter()
        this.receiptList.map(row => {
          row.amount = tool.xe.add(row.nowCheck, row.yhAmount)
        })
        let ramount = tool.xe.sum(this.receiptList, 'nowCheck')
        let backAmount = 0
        if(this.back.list.length > 0) {
          backAmount = -tool.xe.sum(this.back.list, 'amount')
        }
        this.$refs.accountRef.setAmount(tool.add(ramount, backAmount))
      })
    },
    changeCheck (val) {
      this.receiptData = val
    },
    clearData() {
      this.receiptList = []
      this.$refs.backRef.setData([])
      this.updateAll()
    },
    //,
    getAllData () {
      let obj = {
        receiptInfos: this.receiptList,
        back: this.back
      }
      return obj
    }
	},
};
</script>

<style scoped lang="scss">
.iframe {
  width: 100%;
  height: 800px;
  border: none;
}

</style>